//
//  RegisterViewController.m
//  Guazi
//
//  Created by koolearn on 11-6-23.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RegisterViewController.h"
#import "TextFieldCell.h"
#import "ButtonCell.h"
#import "StringUtil.h"
#import "ActivateViewController.h"
#import "GuaziAppDelegate.h"
#import "TwitterClient.h"

#define kTagPhone 101
#define kTagUsername 201
#define kTagPassword 202


@interface RegisterViewController(private)
- (void) setTextFieldValue:(UITextField*)field;
@end


@implementation RegisterViewController

@synthesize textField;
@synthesize phone;
@synthesize username;
@synthesize password;


- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.textField = nil;
        self.phone = nil;
        self.username = nil;
        self.password = nil;
    }
    return self;
}


- (void)dealloc
{
    [textField release];
    [phone release];
    [username release];
    [password release];
    [super dealloc];
}
 

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"注册";
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"放弃" 
                                                                             style:UIBarButtonItemStylePlain 
                                                                            target:self action:@selector(close)] autorelease];
   // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.textField = nil;
    self.phone = nil;
    self.username = nil;
    self.password = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - operations

- (void) close
{
    [self.navigationController popViewControllerAnimated:YES];
    FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
    [controller.navigationController dismissModalViewControllerAnimated:YES];
}


- (void) showAlert:(NSString*)message
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"提示" 
                                                    message:message 
                                                   delegate:nil 
                                          cancelButtonTitle:@"确定" 
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}


- (void) registerPhone
{
    [self setTextFieldValue:textField];
    
    if ( !phone || [phone length] == 0 ) {
        [self showAlert:@"请输入手机号"];
        return;
    }
    
    User* user = [GuaziAppDelegate getAppDelegate].user;
    if ( [user.state compare:kUserStateLocal] != NSOrderedSame ) {
        [self showAlert:@"您已经注册过了"];
        return;
    }
    
    BOOL result = [TwitterClient registerSync:[GuaziAppDelegate getAppDelegate].user.userId name:phone password:user.password];
    if ( !result ) {
        [self showAlert:@"抱歉，注册失败"];
        return;
    }
    
    user.name = phone;
    user.phone = phone;
    user.state = kUserStateUnopen;
    [user updateDB:NO withName:YES withAccount:NO];
    
    ActivateViewController* controller = [[ActivateViewController alloc] initWithStyle:UITableViewStyleGrouped];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


- (void) login
{
    if ( !username || [username length] == 0 ) {
        [self showAlert:@"请输入用户名"];
        return;
    }
    
    if ( !password || [password length] == 0 ) {
        [self showAlert:@"请输入密码"];
        return;
    }
    
    User* user = [TwitterClient verifyAccount:username password:password];
    if ( user ) {
        user.name = username;
        user.password = password;
        [[GuaziAppDelegate getAppDelegate] switchUser:user];
        [self close];
    }
    else {
        [GuaziAppDelegate showAlert:@"验证没有通过，请输入正确的用户名和密码"];
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 1;
    }
    else if (section == 1 ) {
        return 1;
    }
    else if ( section == 2 ) {
        return 2;
    }
    else if ( section == 3 ) {
        return 1;
    }
    else {
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    
    if ( section == 0 ) {
        NSString *CellIdentifier = @"Cell0";
        TextFieldCell *cell = (TextFieldCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        [cell updateWithDelegate:self tag:kTagPhone];
        [cell setKeybordType:UIKeyboardTypeNumberPad];
        
        return cell;
    }
    else if ( section == 1 ) {
        NSString *CellIdentifier = @"Cell1";
        ButtonCell *cell = (ButtonCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[ButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        [cell setTitle:@"继续"];
        
        UIImage* image = [[UIImage imageNamed:@"button_green.png"] stretchableImageWithLeftCapWidth:8 topCapHeight:0];
        [cell setImage:image imagePressed:nil];
        return cell;
    }
    else if ( section == 2 ) {
        NSString *CellIdentifier = @"Cell2";
        TextFieldCell *cell = (TextFieldCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[TextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        if ( row == 0 ) {
            [cell updateWithDelegate:self tag:kTagUsername];
        }
        else {
            [cell updateWithDelegate:self tag:kTagPassword];
            [cell setSecurity:YES];
        }
        
        return cell;
    }
    else if ( section == 3 ) {
        NSString *CellIdentifier = @"Cell3";
        ButtonCell *cell = (ButtonCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[ButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        
        [cell setTitle:@"登录"];
        
        UIImage* image = [[UIImage imageNamed:@"button_green.png"] stretchableImageWithLeftCapWidth:8 topCapHeight:0];
        [cell setImage:image imagePressed:nil];
        return cell;
    }
    else {
        return nil;
    }
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return @"如果您还没有注册，请在下框中输入您的手机号，然后按“继续”:";
    }
    else if ( section == 2 ) {
        return @"如果您已经注册，请输入用户名和密码登录：";
    }
    else {
        return nil;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if ( section == 0 ) {
        return 60;
    }
    else if ( section == 2 ) {
        return 70;
    }
    else {
        return 0;
    }
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate


- (NSIndexPath*) tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ( indexPath.section == 1 || indexPath.section == 3 ) {
        return indexPath;
    }
    else {
        return nil;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    [self setTextFieldValue:textField];
    if ( indexPath.section == 1 ) {
       [self registerPhone];
    }
    else if ( indexPath.section == 3 ) {
        [self login];
    }
}


#pragma mark - TextFieldCell delegate

- (NSString*) label:(NSInteger)tag 
{
    if ( tag == kTagUsername ) {
        return @"用户名";
    }
    else if ( tag == kTagPassword ) {
        return @"密码";
    }
    
    return @"";
}

- (NSString*) text:(NSInteger)tag
{
    return @"";
}

- (CGFloat) labelWidth:(NSInteger)tag
{
    if ( tag == kTagUsername || tag == kTagPassword ) {
        return 60.0f;
    }
    
    return 0.0f;
}


- (NSString*) textFieldPlaceHolder:(NSInteger)tag
{
    if ( tag == kTagPhone ) {
        return @"请输入本机手机号";
    }
    else if ( tag == kTagUsername ) {
        return @"请输入用户名";
    }
    else if ( tag == kTagPassword ) {
        return @"请输入密码";
    }
    else {
        return @"";
    }
}


- (void)textFieldDidBeginEditing:(UITextField *)field
{
	self.textField = field;;
}


- (void) textFieldDidEndEditing:(UITextField *)field
{
    [self setTextFieldValue:field];
}


- (void) setTextFieldValue:(UITextField*)field
{
    if ( !field ) return;
    
    NSInteger tag = textField.tag;
    if ( tag == kTagPhone ) {
        self.phone = [textField.text trim];
    }
    else if ( tag == kTagUsername ) {
        self.username = [textField.text trim];
    }
    else if ( tag == kTagPassword ) {
        self.password = [textField.text trim];
    }
}


@end
